module Logins.UserLogin exposing (..)

import Html exposing (Html, a, button, code, div, h1, li, text, ul, input, br)
import Html.Events exposing (onInput,onClick)
import Http
import Logins.Common as Common
import Json.Encode as Encode
import Navigation exposing (newUrl)

type Msg 
 = NameInput String
 | PassInput String
 | Confirm
 | LoginResult (Result Http.Error (Result ErrorText OkText))

type alias Name = String
type alias Pass = String
type alias ErrorText = String
type alias OkText = String
type alias Log = String


type Model = Model Name Pass Log

initModel : Model
initModel = Model "" "" ""

view : Model -> Html Msg
view (Model name pass log) =
 div [] 
  [ text "用户名: "
  , input [ onInput NameInput ] [ ]
  , text "密码: "
  , input [ onInput PassInput ] [ ]
  , button [ onClick Confirm ] [text "登录"]
  , br [] []
  , text ("Logger: " ++ log) ]

update : Msg -> Model -> (Model,Cmd Msg)
update msg ((Model oldName oldPass log) as model) =
 case msg of
  NameInput name ->
   (Model name oldPass log,Cmd.none)
 
  PassInput pass ->
   (Model oldName pass log,Cmd.none)

  Confirm ->
   let
    url = "/user-end/op/login"
    body = Encode.object [("user",Encode.string oldName),("pass",Encode.string oldPass)]
    post = Http.post url (Http.jsonBody body) Common.loginResDecoder
   in
    (model, Http.send LoginResult post)

  LoginResult (Err _) -> (Model oldName oldPass "服务器响应错误!",Cmd.none)

  LoginResult (Ok res) ->
   case res of
    Err text -> (Model oldName oldPass ("登录失败!" ++ text),Cmd.none)

    Ok _ -> (Model oldName oldPass "登录成功", newUrl "/#/user-end/shop-list")